<?php

namespace app\admin\controller\note;

use app\admin\model\facrm\Customer;
use app\admin\model\note\Okr;
use app\admin\model\note\Task;
use app\common\controller\Backend;
use service\ai\AiService;
use think\Config;
use think\Db;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\response\Json;

/**
 * 目标
 *
 * @icon fa fa-circle-o
 */
class Day extends Backend
{

    /**
     * Day模型对象
     * @var \app\admin\model\note\Day
     */
    protected $model = null;
	protected $relationSearch = true;
	protected $searchFields = ['user.nickname', 'user.phone', 'customer.name', 'contact.name'];


    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\note\Day;
        $this->view->assign("weekDayList", $this->model->getWeekDayList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

	/**
     * 查看
     *
     * @return string|Json
     * @throws \think\Exception
     * @throws DbException
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }

		// 手动筛选
		$filter_w = $this->getFilterWhere();
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();

		$list = $this->model->with(['user','customer','contact','tasks','okrs'])
            ->where($where)->where($filter_w)
            ->order($sort, $order)
			->paginate($limit);
        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }

	private function getFilterWhere(){
		$filter = $this->request->get("filter", '');
        $filter = (array)json_decode($filter, true);
        $filter_w = [];
        $filter['scene_id'] = isset($filter['scene_id']) ? $filter['scene_id'] : 1;

		switch ($filter['scene_id']) {
			case 1:
				$filter_w['day.date_time'] = ['>=', strtotime(date('Y-m-d 00:00:00'))];
				if($this->request->param('all',0)!=1) $filter_w['date_time'] = ['<=',time()];
				break;
			default:
				break;
		}
		unset($filter['scene_id']);

		$this->request->get(['filter' => json_encode($filter)]);

		if($this->request->param('uid',0)!=0) $filter_w['day.uid'] = $this->request->param('uid');
		if($this->request->param('customer_id',0)!=0) $filter_w['day.customer_id'] = $this->request->param('customer_id');
		if($this->request->param('contact_id',0)!=0) $filter_w['day.contact_id'] = $this->request->param('contact_id');


		//非超级管理员只显示自己负责的
		if(!$this->auth->isSuperAdmin()){
			$customer_ids = Customer::where('owner_user_id', $this->auth->id)->whereOr([Db::raw("FIND_IN_SET(" . $this->auth->id . ",owner_user_ids)")])->column('id');
			$filter_w['day.customer_id'] = ['in', $customer_ids];
		}

        return $filter_w;
	}

	/**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $monthDays = [];
			for($n = 1; $n <= 31; $n++){
				$monthDays[$n] = $n;
			}
			$this->view->assign("monthDays", $monthDays);

			$this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

		if(isset($params['notice']) && $params['notice'] && isset($params['feeling']) && $params['feeling'] && ($row->notice != $params['notice'] || $row->feeling != $params['feeling'])) {
			$row->notice = $params['notice'];
			$row->feeling = $params['feeling'];
			$row->okr = Okr::where(['week_id' => $row['week_id']])->select();
			$params['ai_reply'] = $this->aiReply($row);
			$params['ai_reply_time'] = time();
		}

        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $result = $row->allowField(true)->save($params);

			// 本周OKR
			$okrModel = new Okr();
			$okr = json_decode($this->request->post('okr','[]'),true);
			$okrModel->editWeek($okr, $row->week_id, $row->uid, $row->customer_id, $row->contact_id);

			// 今日任务
			$taskModel = new Task();
			$tasks = json_decode($this->request->post('task','[]'),true);
			$taskModel->day($tasks, $row);

            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success('',null,$row->getData());
    }

	protected function aiReply($day)
	{
		$okr_completed = '';
		$okr_uncompleted = '';
		foreach($day->okr as $okr){
			if($okr->status == 1) $okr_completed .= $okr->content . "\n";
			else $okr_uncompleted .= $okr->content . "\n";
		}
		if($okr_completed!='') $okr_completed = "本周已完成目标：\n" . $okr_completed . "\n";
		if($okr_uncompleted!='') $okr_uncompleted = "本周未完成目标：\n" . $okr_uncompleted . "\n";

		$completed = '';
		$uncompleted = '';
		foreach($day->tasks as $task){
			if($task->status == 1) $completed .= $task->content . "\n";
			else $uncompleted .= $task->content . "\n";
		}
		if($completed!='') $completed = "今日已完成任务：\n" . $completed . "\n";
		if($uncompleted!='') $uncompleted = "今日未完成任务：\n" . $uncompleted . "\n";

		$question = $okr_completed . $okr_uncompleted . $completed . $uncompleted;
		if($day->notice) $question .= "我今天察觉到" . $day->notice . "\n";
		if($day->feeling) $question .= "我的感悟：" . $day->feeling . "\n";
		if($day->note) $question .= "咨询师对我的记录：" . $day->note . "\n";
		$question .= '请评价我今日的任务和本周目标的关联关系，然后综合我的本周目标、今天任务的完成情况、我的察觉、我的感悟、咨询师对我的记录对我进行分析，回复尽量简洁';
		$aiService = new AiService(Config::get('ai.dify'));
		return $aiService->textReply('AI成长', $question);
	}
}
